package com.yangrong.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

	public static void main(String[] args) {
		new LockTest().init();
	}

	private void init() {
		final OutPuter output = new OutPuter();
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					output.output("Thread1");
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					output.output("Thread2");
				}
			}
		}).start();
	}

	class OutPuter {
		Lock lock = new ReentrantLock();
//		public void output(String name) {
//			int len = name.length();
//			synchronized (this) {
//				for(int i = 0;i < len; i++) {
//					System.out.print(name.charAt(i));
//				}
//				System.out.println();
//			}
//		}

		public void output(String name) {
			int len = name.length();
			lock.lock();
			try {
				for (int i = 0; i < len; i++) {
					System.out.print(name.charAt(i));
				}
				System.out.println();
			} finally {
				lock.unlock();
			}

			lock.unlock();
		}

//		public synchronized void output(String name) {
//			int len = name.length();
//			for(int i = 0;i < len; i++) {
//				System.out.print(name.charAt(i));
//			}
//			System.out.println();
//		}
	}
}
